package com.hcl.orm.core.executor;

import cn.hutool.core.util.StrUtil;
import com.hcl.orm.core.annotation.DBType;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

/**
 * @author hucl
 * @projectName jim-orm
 * @description: TODO
 * @date 2021/5/1814:16
 */
public class DefaultDataSourceTypeLookup implements DataSourceTypeLookup, InitializingBean {
    private DBType dbType = DBType.ORACLE;

    @Autowired
    private Environment environment;

    @Override
    public DBType getDataSourceType(String pkgName) {
        return dbType;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        String url = environment.getProperty("spring.datasource.url");
        int lIndex = StrUtil.indexOf(url, ':', 0) + 1;
        int rIndex = StrUtil.indexOf(url, ':', lIndex);
        if (StrUtil.sub(url, lIndex, rIndex).equalsIgnoreCase("oceanbase")) {
            int nextIndex = StrUtil.indexOf(url, ':', rIndex + 1);
            if (nextIndex > 0) {
                dbType = DBType.OB_ORC;
            } else {
                dbType = DBType.OB_MYSQL;
            }
        } else {
            dbType = DBType.fromString(StrUtil.sub(url, lIndex, rIndex));
        }
    }
}
